package com.mindbook.vip.gawxchatinfo.utils.file;

import com.mindbook.vip.gawxchatinfo.exception.file.FileUploadException;
import com.mindbook.vip.gawxchatinfo.utils.date.DateUtils;
import com.mindbook.vip.gawxchatinfo.utils.properties.ApplicationContextUtil;
import com.mindbook.vip.gawxchatinfo.utils.result.ResultEnum;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @NAME: wxb
 * @DATE: 2022/6/20
 * @DESCRIPTION: 文件上传接口
 **/
@Component
public class FileUploadUtils {


    public String fileUpload(MultipartFile file, HttpServletRequest request) throws IOException {

        //判断当前文件是否存在
        if (file == null) {
            throw new FileUploadException(ResultEnum.UPLOAD_FILE_EMPTY.getCode(), ResultEnum.UPLOAD_FILE_EMPTY.getMsg());
        }

        //获取当前项目地址
        String requestURL = request.getRequestURL().toString();//项目地址
        String contextPath = request.getContextPath();//项目名

        //1.构建文件的名称：时间戳+.type
        String oldFileName = file.getOriginalFilename();
        String realFileName = System.currentTimeMillis() + oldFileName.substring(oldFileName.indexOf("."), oldFileName.length());
        System.out.println("真实名称是:" + realFileName);
        //2.构建文件保存地址：自定义地址+ 日期时间 + 文件名
        //1.判断文件夹是否存在
        String fileDirectoryPath = ApplicationContextUtil.getProperty("fileupload.save-address") + contextPath + "/" + "file/" + DateUtils.getDateFormat();
        File fileDirectory = new File(fileDirectoryPath);
        if (!fileDirectory.isDirectory()) {
            fileDirectory.mkdirs();
        }
        //2.把数据保存好
        String path = fileDirectory + "/" + realFileName;
        file.transferTo(new File(path));
        //返回真实路径
        String returnUrl = requestURL.substring(0, requestURL.indexOf(contextPath)) + "/image/" + contextPath +
                "/file/" + DateUtils.getDateFormat() + "/" + realFileName;
        return returnUrl;
    }

}
